/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.smarttmt.idu.web.beans;

import com.smarttmt.idu.ejb.domain.Constants;
import com.smarttmt.idu.web.behavior.Preloadable;
import com.smarttmt.idu.web.persistence.controller.UsuacontJpaController;
import com.smarttmt.idu.web.persistence.entity.Usuacont;
import com.smarttmt.idu.web.utilities.FacesUtils;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;

/**
 *
 * @author Nicolás Rubén Caballero Ortega (helaman58@gmail.com)
 */
@Named(value = "activateNewUserBean")
@SessionScoped
public class ActivateNewUser extends SmartIduBackingBean implements Serializable, Preloadable {

    private boolean showAditionalInformation = false;
    @PersistenceUnit(unitName = "smarttmtiduappPU")
    private EntityManagerFactory emf;
    @Resource
    private UserTransaction utx;
    private UsuacontJpaController usuacontJpaController;
    private String userkey;

    /**
     * Creates a new instance of activateNewUser
     */
    public ActivateNewUser() {
        super();
    }

    @PostConstruct
    public void postConstructorActivateNewUser() {
        usuacontJpaController = new UsuacontJpaController(utx, emf);
    }

    public void resetData() {
        this.showAditionalInformation = false;
    }

    public void refreshData() {
    }

    @Override
    public void preload(Map<String, Object> parameters) throws Exception {
        resetData();

        //Se inicializa el bean de la información adicional.
        Preloadable bean = (Preloadable) FacesUtils.getManagedBean("aditionalInformationBean");
        bean.preload(null);
        //Se deben descargar los parámetros de la url

        //Una vez se extrae el key, se busca la activación que esta pendiente con dicho key y se da de alta.
        //Inmediatamente se muestra la información adicional del usuario
    }

    public boolean validaKeyContent(String key) {
        if (key.toUpperCase().contains("SELECT") || key.toUpperCase().contains("UPDATE") || key.toUpperCase().contains("DELETE") || key.toUpperCase().contains("FROM")
                || key.toUpperCase().contains("%")
                || key.toUpperCase().contains("*")) {
            return false;
        }

        return true;
    }

    public void activateUserWithKey(String key) throws Exception {
        this.userkey = null;
        Usuacont usuacont = usuacontJpaController.getUserByUsconomb(key);
        usuacont.setUscoesta(Constants.USER_ACTIVE);
        usuacontJpaController.edit(usuacont);
        this.userkey = key;
    }

    public void loadParametersActivate() throws Exception {
        String key = FacesUtils.getSessionParameter(Constants.KEY_PARAMETER);
        if (key != null) {
            if (!validaKeyContent(key)) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "No ha sido posible activar el usuario", "Comuniquese con nosotros para resolver el problema"));
            } else {
                activateUserWithKey(key);
            }
        }

        showAditionalInformation = true;

    }

    public String registryAditionalInformation() {
        this.showAditionalInformation = true;
        try {
            Preloadable bean = (Preloadable) FacesUtils.getManagedBean("aditionalInformationBean");
            Map<String,Object> parameters = new HashMap<>();
            parameters.put("key", this.userkey);
            bean.preload(parameters);
            return "aditionalInformation";
        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "No ha sido posible habilitar el formulario para completar información", ""));
            return null;
        }

    }

    public boolean isShowAditionalInformation() {
        return showAditionalInformation;
    }

    public void setShowAditionalInformation(boolean showAditionalInformation) {
        this.showAditionalInformation = showAditionalInformation;
    }

    public EntityManagerFactory getEmf() {
        return emf;
    }

    public void setEmf(EntityManagerFactory emf) {
        this.emf = emf;
    }

    public UserTransaction getUtx() {
        return utx;
    }

    public void setUtx(UserTransaction utx) {
        this.utx = utx;
    }

    public UsuacontJpaController getUsuacontJpaController() {
        return usuacontJpaController;
    }

    public void setUsuacontJpaController(UsuacontJpaController usuacontJpaController) {
        this.usuacontJpaController = usuacontJpaController;
    }

    public String getUserkey() {
        return userkey;
    }

    public void setUserkey(String userkey) {
        this.userkey = userkey;
    }

}
